package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"math/rand"
	"strconv"
	"time"
	"zg3yk/dao"
	"zg3yk/inits"
	"zg3yk/pkg"
	"zg3yk/request"
)

func SendSms(c *gin.Context) {
	var req request.SendSms
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	inits.Rdb.Set(context.Background(), "sendSms"+req.Mobile, code, time.Minute*5)
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "ok",
		"data": sms.Body.Message,
	})
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	get, _ := inits.Rdb.Get(context.Background(), "SendSmsIncr"+req.Mobile).Int()
	if get >= 5 {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "错误次数超过5次，请10分钟后重新尝试",
			"data": nil,
		})
		return
	}

	cmd := inits.Rdb.Get(context.Background(), "sendSms"+req.Mobile)
	if cmd.Val() != req.Code {
		inits.Rdb.Incr(context.Background(), "SendSmsIncr"+req.Mobile)

		inits.Rdb.Expire(context.Background(), "SendSmsIncr"+req.Mobile, time.Minute*10)

		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "验证码错误",
			"data": nil,
		})
		return
	}
	user, err := dao.GetUser(req.Mobile)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	if user.ID == 0 {
		err = dao.CreateUser(req.Mobile)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 1000,
				"msg":  err.Error(),
				"data": nil,
			})
			return
		}
	}
	claims := pkg.CustomClaims{
		ID: user.ID,
	}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "成功",
		"data": token,
	})
	inits.Rdb.Del(context.Background(), "sendSms"+req.Mobile)
}
